#pragma once
#include "log.hpp"
#include<sys/types.h>
#include<sys/socket.h>
#include <cstdlib>
#include<netinet/in.h>
#include<cstring>
#include<arpa/inet.h>
#include<functional>
#include "inetaddr.hpp"

using func_t  = std::function<std::string(const std::string&,const InetAddr&)>;

class UdpServer
{
public:
    UdpServer(uint16_t port,func_t func)
    :_port(port)
    ,_isrunning(false)
    ,_func(func)
    {

    }

    ~UdpServer()
    {

    }

    void Init()
    {
        int fd = socket(AF_INET,SOCK_DGRAM,0);
        if(-1 == fd)
        {
            LOG(LogLevel::FATAL) << "socket error";
            exit(1);
        }
        _sockfd = fd;
        LOG(LogLevel::INFO) << "socket success";
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
        if(n == -1)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success";
    }

    void Start()
    {   
        _isrunning = true;
        while(_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t  len  = sizeof(peer);
            ssize_t n = recvfrom(_sockfd,buffer,sizeof(buffer) - 1,0,(struct sockaddr*)&peer,&len);
            if(n == -1)
            {
                LOG(LogLevel::ERROR) << "recvfrom error";
            }
            buffer[n] = 0;
            InetAddr addr(peer); 
            LOG(LogLevel::DEBUG) << "[" << addr.GetIp() << ":"<< addr.GetPort() << "]# " << buffer;
            std::string ret = _func(buffer,addr);
            sendto(_sockfd,ret.c_str(),ret.size(),0,(struct sockaddr*)&peer,len);
        }
    }

private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};